#!/usr/bin/env bash

set -e

CURRENT_DIR=$(pwd)
source ${CURRENT_DIR}/log.sh "$(basename $0 .sh)-log-$(date "+%Y%m%d%H%M%S%1N")"

# 检查是否以 root 用户运行
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        error "请使用 root 用户"
        exit 1
    fi
}

# 卸载旧版本
remove_old_versions() {
    start_info "[1/5] 卸载旧版本 Docker"
    yum remove -y docker \
        docker-client \
        docker-client-latest \
        docker-common \
        docker-latest \
        docker-latest-logrotate \
        docker-logrotate \
        docker-engine
}

# 安装依赖
install_dependencies() {
    start_info "[2/5] 安装依赖包"
    yum install -y yum-utils \
        device-mapper-persistent-data \
        lvm2
}

# 添加 Docker 官方仓库
add_repo() {
    start_info "[3/5] 添加 Docker 仓库"
    yum-config-manager --add-repo \
        https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
}

# 安装 Docker
install_docker() {
    start_info "[4/5] 安装 Docker"
    yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}

# 配置并启动 Docker
configure_docker() {
    start_info "[5/5] 配置并启动 Docker 服务"

    if [ -f /etc/docker/daemon.json ]; then
        info "备份原 daemon.json 文件"
        mv -v /etc/docker/daemon.json "/etc/docker/daemon.json.$(date "+%Y%m%d%H%M%S%1N")"
    fi

    info "创建新的 daemon.json 文件"
    cat > "/etc/docker/daemon.json" <<EOF
{
    "registry-mirrors": ["https://docker.m.daocloud.io"],
    "log-opts": {
        "max-size": "50m",
        "max-file":"3"
      }
}
EOF

    info "启动 Docker 服务并设置开机自启动"
    systemctl start docker
    systemctl enable docker

    # 验证安装
    info "\nDocker 已成功安装！版本信息："
    docker --version
}

# 主执行流程
main() {
    check_root
    remove_old_versions
    install_dependencies
    add_repo
    install_docker
    configure_docker
}

main "$@"
